package com.example.test_witns.utils;

import android.graphics.Bitmap;
import android.graphics.Color;
import android.widget.ImageView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.nio.charset.StandardCharsets;
import java.util.Hashtable;

public class QrCodeUtils {
    public static void generateTransparentQrCode(String content, ImageView imageView) {
        QRCodeWriter writer = new QRCodeWriter();
        try {
            // 设置二维码参数（去除边框）
            Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
            hints.put(EncodeHintType.MARGIN, 0); // 关键：去除白边

            byte[] contentBytes;
            contentBytes = content.getBytes(StandardCharsets.UTF_8);

            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");

            // 生成二维码矩阵
            BitMatrix bitMatrix = writer.encode(new String(contentBytes, StandardCharsets.ISO_8859_1),
                BarcodeFormat.QR_CODE,
                512,  // 宽度
                512,  // 高度
                hints // 应用参数
            );

            // 创建支持透明的 Bitmap
            int width = bitMatrix.getWidth();
            int height = bitMatrix.getHeight();
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); // 关键：支持透明度
            
            // 填充像素
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    int color = bitMatrix.get(x, y) ? 
                        Color.argb(160,147, 107, 217) :     // 二维码前景色
                        Color.TRANSPARENT; // 背景透明
                    bitmap.setPixel(x, y, color);
                }
            }
            
            imageView.setImageBitmap(bitmap);
            
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }
}